#include "qvideothread.h"
#include "xffmpeg.h"
#include "xaudioplay.h"
#include <list>

bool isexit = false;
static std::list<AVPacket> videos;
static int apts = -1;

QVideoThread::QVideoThread()
{
}
QVideoThread::~QVideoThread()
{
}

void QVideoThread::run()
{
    char *out = new char[10000];
    while(!isexit)
    {
        if(!XFFmpeg::Get()->GetIsPlay())
        {
            msleep(10);
            continue;
        }

        while (videos.size() > 0) {
            AVPacket pack = videos.front();
            int pts = XFFmpeg::Get()->GetPTS(&pack);
            if(pts > apts)
            {
               break;
            }
            XFFmpeg::Get()->Decode(pack);
            av_packet_unref(&pack);
            videos.pop_front();
        }
        int free = XAudioPlay::Get()->GetFree();
        if(free < 4096)
        {
            msleep(1);
            continue;
        }
        AVPacket pkt = XFFmpeg::Get()->Read();
        if(pkt.size <= 0)
        {
            msleep(10);
            continue;
        }
        if(pkt.stream_index == XFFmpeg::Get()->GetAudioStream())
        {
            apts = XFFmpeg::Get()->Decode(pkt);
            av_packet_unref(&pkt);
            int len = XFFmpeg::Get()->ToPCM(out);
            XAudioPlay::Get()->Write(out, len);
            continue;
        }
        if(pkt.stream_index != XFFmpeg::Get()->GetVideoStream())
        {
            av_packet_unref(&pkt);
            continue;
        }
//        XFFmpeg::Get()->Decode(pkt);
//        av_packet_unref(&pkt);
        videos.push_back(pkt);
    }
    delete []out;
}

void QVideoThread::end()
{
    isexit = true;
}
